<template>
  <div class="layout-container bg-gray-50 dark:bg-dark-950 transition-colors duration-300">
    <!-- Mobile sidebar overlay -->
    <div
      v-if="appStore.sidebarMobileOpen"
      class="fixed inset-0 z-40 lg:hidden"
      @click="appStore.setMobileSidebarOpen(false)"
    >
      <div class="absolute inset-0 bg-black opacity-50"></div>
    </div>

    <!-- Sidebar -->
    <aside
      :class="[
        'layout-sidebar fixed inset-y-0 left-0 z-50 transform transition-all duration-300 ease-in-out lg:relative lg:translate-x-0',
        {
          'translate-x-0': appStore.sidebarMobileOpen,
          '-translate-x-full': !appStore.sidebarMobileOpen,
          'w-20': appStore.sidebarCollapsed,
          'w-72': !appStore.sidebarCollapsed
        }
      ]"
    >
      <div class="flex h-full flex-col glass-dark dark:glass-dark lg:glass-light lg:dark:glass-dark border-r border-gray-200 dark:border-dark-700">
        <!-- Logo section -->
        <div class="flex h-16 flex-shrink-0 items-center px-6 border-b border-gray-200 dark:border-dark-700">
          <div class="flex items-center space-x-3">
            <div class="flex-shrink-0">
              <div class="w-8 h-8  rounded-lg flex items-center justify-center">
               <img src="/logo.png" alt="logo" class="w-8 h-8"/>
              </div>
            </div>
            <div
              v-if="!appStore.sidebarCollapsed"
              class="flex flex-col"
            >
              <h1 class="text-lg font-bold text-gradient">X-Synergy OS</h1>
              <p class="text-xs text-gray-500 dark:text-gray-400">AI驱动的智能管理系统</p>
            </div>
          </div>
        </div>

        <!-- User info -->
      

        <!-- Navigation -->
        <nav class="flex-1 space-y-1 px-3 py-4 overflow-y-auto">
          <!-- 系统菜单 -->
          <div class="mb-4">
            <div v-if="!appStore.sidebarCollapsed" class="px-3 py-2 text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
              系统功能
            </div>
            <router-link
              v-for="route in menuRoutes"
              :key="route.name"
              :to="route.path"
              :class="[
                'group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-all duration-200',
                {
                  'bg-primary-100 dark:bg-primary-900/20 text-primary-700 dark:text-primary-300 border-l-4 border-primary-500': $route.name === route.name,
                  'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-dark-800 hover:text-gray-900 dark:hover:text-gray-100': $route.name !== route.name
                }
              ]"
            >
             <Icon :icon="route.meta?.icon as string" class="w-5 h-5 flex-shrink-0" :class="[
                  appStore.sidebarCollapsed ? 'mr-0' : 'mr-3',
                  {
                    'text-primary-600 dark:text-primary-400': $route.name === route.name,
                    'text-gray-500 dark:text-gray-400 group-hover:text-gray-700 dark:group-hover:text-gray-300': $route.name !== route.name
                  }
                ]" />
              <span v-if="!appStore.sidebarCollapsed">
                {{ route.meta?.title }}
              </span>
            </router-link>
          </div>

          <!-- 动态菜单 -->
          <div v-if="visibleDynamicMenus.length > 0">
            <div v-if="!appStore.sidebarCollapsed" class="px-3 py-2 text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
              数据管理
            </div>
            <div class="mb-2 border-t border-gray-200 dark:border-dark-700 pt-2">
              <a
                v-for="menu in visibleDynamicMenus"
                :key="menu.key"
                href="#"
                @click.prevent="handleDynamicMenuClick(menu)"
                :class="[
                  'group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-all duration-200',
                  {
                    'bg-primary-100 dark:bg-primary-900/20 text-primary-700 dark:text-primary-300 border-l-4 border-primary-500': $route.query.table === menu.table_name,
                    'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-dark-800 hover:text-gray-900 dark:hover:text-gray-100': $route.query.table !== menu.table_name
                  }
                ]"
              >
                <component
                  :is="getDynamicIcon(menu.icon)"
                  class="w-5 h-5 flex-shrink-0"
                  :class="[
                    appStore.sidebarCollapsed ? 'mr-0' : 'mr-3',
                    {
                      'text-primary-600 dark:text-primary-400': $route.query.table === menu.table_name,
                      'text-gray-500 dark:text-gray-400 group-hover:text-gray-700 dark:group-hover:text-gray-300': $route.query.table !== menu.table_name
                    }
                  ]"
                />
                <span v-if="!appStore.sidebarCollapsed">
                  {{ menu.name }}
                </span>
              </a>
            </div>
          </div>
        </nav>

        <!-- Theme toggle & settings -->
        <div class="border-t border-gray-200 dark:border-dark-700 p-4 space-y-2">
          <!-- Theme toggle -->
          <button
            @click="themeStore.toggleTheme"
            :class="[
              'w-full flex items-center px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-dark-800 transition-all duration-200',
              appStore.sidebarCollapsed ? 'justify-center' : 'justify-start'
            ]"
          >
            <Icon v-if="themeStore.isDark" icon="carbon:sun" class="w-5 h-5" :class="appStore.sidebarCollapsed ? 'mr-0' : 'mr-3'" />
            <Icon v-else icon="carbon:moon" class="w-5 h-5" :class="appStore.sidebarCollapsed ? 'mr-0' : 'mr-3'" />
            <span v-if="!appStore.sidebarCollapsed">
              {{ themeStore.isDark ? '亮色模式' : '暗色模式' }}
            </span>
          </button>

          <!-- Collapse toggle (desktop only) -->
          <button
            @click="appStore.toggleSidebar"
            class="hidden lg:flex w-full items-center px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-dark-800 transition-all duration-200"
            :class="appStore.sidebarCollapsed ? 'justify-center' : 'justify-start'"
          >
            <Icon
              v-if="!appStore.sidebarCollapsed"
              icon="carbon:chevron-left"
              class="w-5 h-5 mr-3"
            />
            <Icon
              v-else
              icon="carbon:chevron-right"
              class="w-5 h-5 mr-0"
            />
            <span v-if="!appStore.sidebarCollapsed">收起菜单</span>
          </button>

          <!-- Logout -->
          <button
            @click="handleLogout"
            :class="[
              'w-full flex items-center px-3 py-2 text-sm font-medium text-red-600 dark:text-red-400 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-all duration-200',
              appStore.sidebarCollapsed ? 'justify-center' : 'justify-start'
            ]"
          >
            <Icon icon="carbon:logout" class="w-5 h-5" :class="appStore.sidebarCollapsed ? 'mr-0' : 'mr-3'" />
            <span v-if="!appStore.sidebarCollapsed">退出登录</span>
          </button>
        </div>
      </div>
    </aside>

    <!-- Main content -->
    <div class="layout-main">
      <!-- Top bar - 固定高度64px -->
      <header class="layout-header bg-white dark:bg-dark-900 shadow-sm border-b border-gray-200 dark:border-dark-700">
        <div class="flex h-full items-center justify-between px-4 sm:px-6 lg:px-8">
          <!-- Mobile menu button -->
          <button
            @click="appStore.toggleMobileSidebar"
            class="lg:hidden p-2 text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          >
            <Icon icon="carbon:menu" class="w-6 h-6" />
          </button>

          <!-- Breadcrumbs -->
          <nav class="hidden sm:flex flex-1" aria-label="Breadcrumb">
            <ol class="flex items-center space-x-2">
              <li v-for="(breadcrumb, index) in appStore.breadcrumbs" :key="index">
                <div class="flex items-center">
                  <Icon
                    v-if="index > 0"
                    icon="carbon:chevron-right"
                    class="w-4 h-4 text-gray-400 dark:text-gray-500 mr-2"
                  />
                  <router-link
                    v-if="breadcrumb.path"
                    :to="breadcrumb.path"
                    class="text-sm font-medium text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"
                  >
                    {{ breadcrumb.name }}
                  </router-link>
                  <span
                    v-else
                    class="text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ breadcrumb.name }}
                  </span>
                </div>
              </li>
            </ol>
          </nav>

          <!-- Right side actions -->
          <div class="flex items-center space-x-2">
            <!-- AI Theme Recommendation -->
            <button
              @click="suggestTheme"
              class="p-2 text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg transition-colors"
              title="AI推荐主题"
            >
              <SwatchIcon class="w-5 h-5" />
            </button>


            <!-- Fullscreen Toggle -->
            <button
              @click="toggleFullscreen"
              class="p-2 text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-all duration-200"
              :title="isFullscreen ? '退出全屏' : '进入全屏'"
            >
              <ArrowsPointingOutIcon v-if="!isFullscreen" class="w-5 h-5" />
              <ArrowsPointingInIcon v-else class="w-5 h-5" />
            </button>

            <!-- Notifications -->
            <div class="relative">
              <button
                @click="showNotifications = !showNotifications"
                class="p-2 text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-all duration-200 relative"
              >
                <Icon icon="carbon:notification" class="w-5 h-5" />
                <span
                  v-if="appStore.unreadNotifications > 0"
                  class="absolute -top-0.5 -right-0.5 w-5 h-5 bg-red-500 text-white text-xs rounded-full flex items-center justify-center"
                >
                  {{ appStore.unreadNotifications > 9 ? '9+' : appStore.unreadNotifications }}
                </span>
              </button>
              
              <!-- Notifications dropdown -->
              <div
                v-if="showNotifications"
                class="absolute right-0 mt-2 w-80 bg-white dark:bg-dark-800 rounded-lg shadow-lg border border-gray-200 dark:border-dark-700 z-10"
                @click.stop
              >
                <div class="p-4 border-b border-gray-200 dark:border-dark-700">
                  <h3 class="text-sm font-medium text-gray-900 dark:text-gray-100">通知</h3>
                </div>
                <div class="max-h-96 overflow-y-auto">
                  <div
                    v-if="appStore.notifications.length === 0"
                    class="p-4 text-center text-gray-500 dark:text-gray-400"
                  >
                    暂无通知
                  </div>
                  <div
                    v-for="notification in appStore.notifications.slice(0, 10)"
                    :key="notification.id"
                    :class="[
                      'p-4 border-b border-gray-100 dark:border-dark-700 last:border-b-0 hover:bg-gray-50 dark:hover:bg-dark-700 cursor-pointer',
                      { 'bg-blue-50 dark:bg-blue-900/10': !notification.read }
                    ]"
                    @click="appStore.markNotificationRead(notification.id)"
                  >
                    <div class="flex items-start space-x-3">
                      <div
                        :class="[
                          'w-2 h-2 rounded-full mt-2 flex-shrink-0',
                          {
                            'bg-green-500': notification.type === 'success',
                            'bg-red-500': notification.type === 'error',
                            'bg-yellow-500': notification.type === 'warning',
                            'bg-blue-500': notification.type === 'info'
                          }
                        ]"
                      ></div>
                      <div class="flex-1">
                        <p class="text-sm font-medium text-gray-900 dark:text-gray-100">
                          {{ notification.title }}
                        </p>
                        <p v-if="notification.message" class="text-sm text-gray-600 dark:text-gray-400 mt-1">
                          {{ notification.message }}
                        </p>
                        <p class="text-xs text-gray-400 dark:text-gray-500 mt-2">
                          {{ formatTime(notification.timestamp) }}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="p-4 border-t border-gray-200 dark:border-dark-700">
                  <button
                    @click="appStore.markAllNotificationsRead"
                    class="text-sm text-primary-600 dark:text-primary-400 hover:text-primary-700 dark:hover:text-primary-300"
                  >
                    全部标记为已读
                  </button>
                </div>
              </div>
            </div>


            <!-- User menu -->
            <div class="relative">

              <button
                @click="showUserMenu = !showUserMenu"
                class="flex items-center space-x-2 p-2 text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-200"
              >

                <div class="w-8 h-8  rounded-full p-0.5 shadow-sm">

                  <div class="w-full h-full rounded-full flex items-center justify-center overflow-hidden">

                    <img
                      src="@/assets/images/user.png" 
                      alt="用户头像" 
                      class="w-full h-full object-contain"
                      @error="handleImageError"
                    />

                  </div>

                </div>
                <div class="hidden sm:block text-left">
                  
                  <div class="text-sm font-medium text-gray-900 dark:text-gray-100">
                    {{ getUserData()?.realName || authStore.user?.username || 'User' }} 
                  </div>
                  <div class="text-sm text-gray-500 dark:text-gray-400">
                    {{ authStore.user?.email || 'user@example.com' }}   
                  </div>
                </div>
                <ChevronDownIcon class="w-4 h-4" />
              </button>
              
              <!-- User dropdown -->
              <div
                v-if="showUserMenu"
                class="absolute right-0 mt-2 w-72 bg-white dark:bg-dark-800 rounded-lg shadow-lg border border-gray-200 dark:border-dark-700 z-10"
                @click.stop
              >
                <div class="p-4 border-b border-gray-200 dark:border-dark-700">
                  <div class="flex items-center space-x-3">
                    
                    <div class="flex-1 min-w-0">
                      <div class="flex items-center space-x-2 mb-1">
                        <p class="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate">
                          {{ getUserData()?.realName || authStore.user?.name || 'User' }}
                        </p>
                    </div>

                    <p class="text-xs text-gray-500 dark:text-gray-400 truncate">
                        {{ authStore.user?.email || 'user@example.com' }}
                    </p>

                     <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                        @{{ authStore.user?.username }}
                     </p>

                    </div>
                  </div>
                  <!-- 权限概览 -->
                  <div v-if="getUserData()?.roles?.[0]?.code === 'super_admin'" class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">
                    <div class="flex items-center justify-center p-2 bg-gradient-to-r from-purple-50 to-indigo-50 dark:from-purple-900/20 dark:to-indigo-900/20 rounded-lg">
                      <span class="text-xs font-medium text-purple-700 dark:text-purple-300">
                         拥有系统全部权限
                      </span>
                    </div>
                  </div>
                  <div v-else-if="authStore.user?.permissions && authStore.user.permissions.length > 0" class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">
                    <div class="flex items-center justify-between mb-2">
                      <span class="text-xs font-medium text-gray-600 dark:text-gray-400">权限概览</span>
                      <span class="text-xs text-primary-600 dark:text-primary-400 font-medium">
                        {{ authStore.user.permissions.length }} 项
                      </span>
                    </div>
                  </div>
                </div>
                <div class="py-2">
                  <router-link
                    to="/settings"
                    class="flex items-center px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-dark-700"
                    @click="showUserMenu = false"
                  >
                    <CogIcon class="w-4 h-4 mr-3" />
                    设置
                  </router-link>
                  <button
                    @click="handleLogout"
                    class="w-full flex items-center px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20"
                  >
                    <ArrowRightOnRectangleIcon class="w-4 h-4 mr-3" />
                    退出登录
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </header>

      <!-- Page content - 中间滚动区域 -->
      <main class="layout-content">
        <div class="h-full py-6 px-4 sm:px-6 lg:px-8">
          <router-view />
        </div>
      </main>

      <!-- Footer - 固定高度48px -->
      <footer class="layout-footer bg-white dark:bg-dark-900 border-t border-gray-200 dark:border-dark-700">
        <div class="flex h-full items-center justify-between px-4 sm:px-6 lg:px-8">
          <!-- 左侧版权信息 -->
          <div class="flex items-center space-x-4">
            <p class="text-sm text-gray-500 dark:text-gray-400">
              © 2025 X-Synergy OS. All rights reserved.
            </p>
          </div>

          <!-- 中间状态信息 -->
          <div class="hidden md:flex items-center space-x-4">
            <!-- 在线状态 -->
            <div class="flex items-center space-x-2">
              <div
                :class="[
                  'w-2 h-2 rounded-full',
                  appStore.isOnline ? 'bg-green-500' : 'bg-red-500'
                ]"
              ></div>
              <span class="text-xs text-gray-500 dark:text-gray-400">
                {{ appStore.isOnline ? '在线' : '离线' }}
              </span>
            </div>

            <!-- 当前版本 -->
            <div class="text-xs text-gray-500 dark:text-gray-400">
              v{{ appStore.appInfo.version }}
            </div>
          </div>

          <!-- 右侧快捷链接 -->
          <div class="flex items-center space-x-4">
            <button
              @click="showHelp"
              class="text-xs text-gray-500 dark:text-gray-400 hover:text-primary-500 dark:hover:text-primary-400 transition-colors"
            >
              帮助
            </button>
            <button
              @click="showAbout"
              class="text-xs text-gray-500 dark:text-gray-400 hover:text-primary-500 dark:hover:text-primary-400 transition-colors"
            >
              关于
            </button>
          </div>
        </div>
      </footer>
    </div>

    <!-- Loading overlay -->
    <div
      v-if="appStore.loading"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
      <div class="bg-white dark:bg-dark-800 rounded-lg p-6 flex items-center space-x-4">
        <div class="loading-spinner w-6 h-6 border-2 border-primary-500 border-t-transparent rounded-full"></div>
        <span class="text-gray-900 dark:text-gray-100">加载中...</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { useAppStore } from '@/store/app'
import { useThemeStore } from '@/store/theme'
import { useMenuStore } from '@/store/menu'
import { getMenuRoutes } from '@/router'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { Icon } from '@iconify/vue'
import { ArrowsPointingOutIcon, ArrowsPointingInIcon, SwatchIcon, CogIcon, ArrowRightOnRectangleIcon, ChevronDownIcon } from '@heroicons/vue/24/outline'
const router = useRouter()
const authStore = useAuthStore()
const appStore = useAppStore()
const themeStore = useThemeStore()
const menuStore = useMenuStore()
// Local state
const showNotifications = ref(false)
const showUserMenu = ref(false)
const isFullscreen = ref(false)
const themeLoading = ref(false)

// Computed
const menuRoutes = computed(() => {
  return getMenuRoutes().filter(route => {
    if (!route.meta?.permissions || !Array.isArray(route.meta.permissions) || route.meta.permissions.length === 0) {
      return true
    }
    return authStore.hasAnyPermission(route.meta.permissions as string[])
  })
})

const visibleDynamicMenus = computed(() => {
  return menuStore.getVisibleMenus()
})


const suggestTheme = () => {
  // AI-driven theme suggestion based on time and usage
  const hour = new Date().getHours()
  const isWorkingHours = hour >= 9 && hour <= 17
  
  let suggestion = ''
  let newTheme = themeStore.mode
  
  if (isWorkingHours) {
    if (themeStore.isDark) {
      suggestion = '检测到您正在工作时间使用系统，建议切换到亮色主题以获得更好的数据阅读体验。'
      newTheme = 'light'
    } else {
      suggestion = '当前亮色主题很适合工作时间的数据查看和分析。'
    }
  } else {
    if (themeStore.isLight) {
      suggestion = '检测到您在非工作时间使用系统，建议切换到暗色主题以减少眼部疲劳。'
      newTheme = 'dark'
    } else {
      suggestion = '当前暗色主题很适合夜间使用，有助于保护视力。'
    }
  }
  
  appStore.showInfo(suggestion)
  
  if (newTheme !== themeStore.mode) {
    setTimeout(() => {
      if (confirm('是否立即切换主题？')) {
        themeStore.setMode(newTheme)
        appStore.showSuccess('主题已切换')
      }
    }, 2000)
  }
}

// Methods
const getIcon = (iconName?: string) => {
  const iconMap: Record<string, string> = {
    'ChatBubbleOvalLeftEllipsisIcon': 'carbon:chat',
    'ClockIcon': 'carbon:time',
    'CogIcon': 'carbon:settings',
    'DocumentTextIcon': 'carbon:document'
  }
  return iconMap[iconName || ''] || 'carbon:chat'
}

const getDynamicIcon = (iconName?: string) => {
  const iconMap: Record<string, string> = {
    'UserGroupIcon': 'carbon:user-multiple',
    'ShieldCheckIcon': 'carbon:security',
    'KeyIcon': 'carbon:security', // 权限图标用security代替
    'TableCellsIcon': 'carbon:table',
    'ArchiveBoxIcon': 'carbon:archive',
    'DocumentTextIcon': 'carbon:document',
    'CogIcon': 'carbon:settings'
  }
  return iconMap[iconName || ''] || 'carbon:table'
}

const handleDynamicMenuClick = (menu: any) => {
  // 导航到动态表格视图页面，传递表名参数
  router.push({
    name: 'DynamicTable',
    query: {
      table: menu.table_name,
      menu: menu.key
    }
  })
}

const formatTime = (date: Date | undefined) => {
  if (!date) return ''
  return formatDistanceToNow(date, { 
    addSuffix: true,
    locale: zhCN
  })
}

const handleLogout = async () => {
  showUserMenu.value = false
  await authStore.logout()
  router.push('/login')
}


// 全屏切换
const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen().then(() => {
      isFullscreen.value = true
      appStore.showSuccess('已进入全屏模式')
    }).catch(() => {
      appStore.showError('无法进入全屏模式')
    })
  } else {
    document.exitFullscreen().then(() => {
      isFullscreen.value = false
      appStore.showSuccess('已退出全屏模式')
    }).catch(() => {
      appStore.showError('无法退出全屏模式')
    })
  }
}



// 处理头像加载错误
const handleImageError = (event: Event) => {

  const target = event.target as HTMLImageElement

  target.style.display = 'none'
  // 可以设置一个默认头像或者显示用户名首字母
  const parent = target.parentElement
  if (parent) {
    parent.innerHTML = `<span class="text-primary-600 dark:text-primary-400 font-bold text-lg">${authStore.user?.name?.charAt(0) || 'U'}</span>`
  }
}


// 获取用户扩展数据的辅助函数

const getUserData = () => {
  return authStore.user as any
}


// Footer event handlers
const showHelp = () => {
  // 打开帮助文档
  window.open('https://docs.x-synergy.com', '_blank')
}

const showAbout = () => {
  // 显示关于对话框
  alert(`关于 X-Synergy OS\n\n版本 ${appStore.appInfo.version}\nAI驱动的智能ERP系统`)
}

const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as Element
  if (!target.closest('.relative')) {
    showNotifications.value = false
    showUserMenu.value = false
  }
}

// 监听全屏状态变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement
}

onMounted(async () => {
  document.addEventListener('click', handleClickOutside)
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  
  // 初始化全屏状态
  isFullscreen.value = !!document.fullscreenElement
  
  // 初始化动态菜单
  try {
    await menuStore.initialize()
  } catch (error) {
    console.error('初始化动态菜单失败:', error)
  }
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
})
</script>

<style scoped>
.loading-spinner {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* Layout主要结构样式 */
.layout-container {
  min-height: 100vh;
  display: flex;
}

.layout-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  overflow: hidden;
}

.layout-header {
  height: 64px;
  flex-shrink: 0;
}

.layout-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.layout-footer {
  height: 48px;
  flex-shrink: 0;
}
</style>
